/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.siglo21.ppo.persistence;

import ar.com.siglo21.ppo.util.TrabajoIntegradorException;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class MySQLConnection {
    
    public Connection conn;
    public static MySQLConnection db;

    private MySQLConnection() throws TrabajoIntegradorException {
        String url= "jdbc:mysql://localhost:3306/";
        String dbName = "trabajointegrador";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "admin";
        try {
            Class.forName(driver).newInstance();
            this.conn = (Connection)DriverManager.getConnection(url+dbName,userName,password);
        }
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException sqle) {
            
            throw new TrabajoIntegradorException(sqle.getMessage());
        }
    }
    /**
     *
     * @return MysqlConnect Database connection object
     */
    public static synchronized MySQLConnection getDbCon() throws TrabajoIntegradorException {
        if ( db == null ) {
            db = new MySQLConnection();
        }
        return db;
 
    }
    /**
     *
     * @param query String The query to be executed
     * @return a ResultSet object containing the results or null if not available
     * @throws SQLException
     */
    public ResultSet query(String query) throws SQLException{
        Statement statement = db.conn.createStatement();
        ResultSet res = statement.executeQuery(query);
        return res;
    }
    
    
    public void insertORDeleteORUpdate(String query) throws SQLException {
       Statement statement = db.conn.createStatement();
       statement.executeUpdate(query);
        
    }
    
              
    
    public ResultSet queryPrepareStatement(String query) throws SQLException{
        Statement statement = db.conn.prepareStatement(query);
        
        ResultSet res = statement.executeQuery(query);
        return res;
    }
 
}